package io.kiki.sba.registry.server.data_store.slot;

import io.kiki.sba.registry.common.model.Tuple;
import io.kiki.sba.registry.common.model.slot.BaseSlotStatus;
import io.kiki.sba.registry.common.model.slot.Slot;
import io.kiki.sba.registry.common.model.slot.SlotAccess;
import io.kiki.sba.registry.common.model.slot.func.SlotFunction;
import io.kiki.sba.registry.common.model.slot.func.SlotFunctionRegistry;
import io.kiki.sba.registry.server.data_store.bootstrap.ServerConfig;
import io.kiki.sba.registry.server.data_store.multi.cluster.slot.MultiClusterSlotManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class SlotAccessorDelegate implements SlotAccessor {

    private final SlotFunction slotFunction = SlotFunctionRegistry.getSlotFunction();
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private SlotManager slotManager;
    @Autowired
    private MultiClusterSlotManager multiClusterSlotManager;

    @Override
    public int slotOf(String dataInfoId) {
        return slotFunction.slotOf(dataInfoId);
    }

    @Override
    public Slot getSlot(String dataCenter, int slotId) {
        return accessOf(dataCenter).getSlot(dataCenter, slotId);
    }

    @Override
    public SlotAccess checkSlotAccess(String dataCenter, int slotId, long srcSlotEpoch, long srcLeaderEpoch) {
        return accessOf(dataCenter).checkSlotAccess(dataCenter, slotId, srcSlotEpoch, srcLeaderEpoch);
    }

    @Override
    public boolean isLeader(String dataCenter, int slotId) {
        return accessOf(dataCenter).isLeader(dataCenter, slotId);
    }

    @Override
    public boolean isFollower(String dataCenter, int slotId) {
        return accessOf(dataCenter).isFollower(dataCenter, slotId);
    }

    @Override
    public Tuple<Long, List<BaseSlotStatus>> getslotsEpochAndStatuses(String dataCenter) {
        return accessOf(dataCenter).getslotsEpochAndStatuses(dataCenter);
    }

    private SlotAccessor accessOf(String dataCenter) {
        return StringUtils.equalsIgnoreCase(serverConfig.getDataCenter(), dataCenter) ? slotManager : multiClusterSlotManager;
    }
}
